package com.wk.cart.interceptor;

import com.wk.cart.config.JwtProperties;
import com.wk.common.bean.UserInfo;
import com.wk.common.utils.CookieUtils;
import com.wk.common.utils.JwtUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.UUID;

/**
 * 声明自定义拦截器
 * 判断用户登录状态 获取token信息 传递给后续业务逻辑
 */
@Component
@EnableConfigurationProperties(JwtProperties.class)
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtProperties jwtProperties;

    /*每个线程独立存放user信息
    ThreadLocal本质是一个map,用于资源隔离和参数传递 泛型是要传递的数据类型
    当前线程对象作为key value存放要传递的数据*/
    private static final ThreadLocal<UserInfo> THREAD_LOCAL = new ThreadLocal<>();

    /**
     * controlle方法执行前 统一获取登录状态
     * 返回true：放行；false：拦截
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        UserInfo userInfo = new UserInfo();

        //获取cookie中的token和userKey信息
        String token = CookieUtils.getCookieValue(request, jwtProperties.getCookieName());
        String userKey = CookieUtils.getCookieValue(request, jwtProperties.getUserKey());

        //userKey不存在则生成一个放入cookie
        if (StringUtils.isBlank(userKey)) {
            userKey = UUID.randomUUID().toString();
            CookieUtils.setCookie(request, response, jwtProperties.getUserKey(), userKey, 6*30*24*3600, "utf-8");
        }
        userInfo.setUserKey(userKey);

        //token存在则解析
        if(StringUtils.isNotBlank(token)){
            Map<String, Object> tokenInfo = JwtUtils.getInfoFromToken(token, jwtProperties.getPublicKey());
            userInfo.setId(new Long(tokenInfo.get("id").toString()));
        }

        //将user信息放入ThreadLocal
        THREAD_LOCAL.set(userInfo);

        return true;
    }

    /**
     * 从ThreadLocal中获取当前线程对象存放的user信息
     */
    public static UserInfo getUserInfo(){
        return THREAD_LOCAL.get();
    }

    /**
     * controller方法结束后手动删除ThreadLocal中存放的线程变量
     * Tomcat线程池的线程不会销毁 手动删除避免Tomcat内存泄漏
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        THREAD_LOCAL.remove();
    }

}
